package com.example.mysqljdbc;


import java.sql.*;

public class MySQLConnection {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            // 1. 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 2. 设置数据库连接参数
            String url = "jdbc:mysql://localhost:3306/mydb?useSSL=true&serverTimezone=Asia/Shanghai&autoReconnect=true&useUnicode=true&characterEncoding=UTF-8";
            String user = "root";
            String password = "123456";

            // 3. 建立数据库连接
            conn = DriverManager.getConnection(url, user, password);

            // 4. 测试连接是否成功
            if (conn != null) {
                System.out.println("MySQL数据库连接成功！");

                // 5. 执行简单的查询示例
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT 1");

                if (rs.next()) {
                    System.out.println("数据库查询测试成功！");
                }

                // 6. 关闭资源
                rs.close();
                stmt.close();
            }

        } catch (ClassNotFoundException e) {
            System.err.println("找不到MySQL JDBC驱动：" + e.getMessage());
        } catch (SQLException e) {
            System.err.println("数据库连接失败：" + e.getMessage());
        } finally {
            // 7. 关闭连接
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("数据库连接已关闭。");
                } catch (SQLException e) {
                    System.err.println("关闭连接时出错：" + e.getMessage());
                }
            }
        }
    }
}
